import { $portal } from '@/util/axios'

const $fairCmd = param => {

  let url = param.url;
  let data = param.data
  let method = param.method
  // return $portal({
  //   url: url,
  //   method: method,
  //   data: data
  // })
  let ContentType = 'application/json; charset=utf-8'
  let dataStr = '' // 数据拼接字符串
  if (typeof param.methods === 'undefined') {
    param.methods = 'POST'
  }
  if (param.methods.toLocaleUpperCase() === 'POST' && ContentType === 'application/x-www-form-urlencoded') {
    Object.keys(param.data).forEach(key => {
      dataStr += encodeURIComponent(key) + '=' + encodeURIComponent(param.data[key]) + '&'
    })
    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
    }
  } else {
    // json 走这里
    dataStr = param.data
  }
  return new Promise(
      function (resolve, reject) {
        $portal({
          baseURL: process.env.VUE_APP_API_BASE,
          url: param.url,
          method: param.methods || 'post',
          data: param.methods === 'POST' || param.methods === 'PUT' || param.methods === 'PATCH' || param.methods === 'DELETE' ? dataStr : null,
          params: param.methods === 'GET' ? dataStr : null,
          // data: dataStr,
          headers: {
            'Content-Type': ContentType,
            'X-Requested-With': 'XMLHttpRequest',
            'X-URL-PATH': location.pathname,
          }
        }).then(
            success => {
                if (success.status !== 200) {
                  reject(success);
                } else {
                  if (success.hasOwnProperty('result')) {
                    success.result = success.result || {}
                    if (typeof success.result === 'object' && !Array.isArray(success.result)) {
                      success.result.message = success.result.message || success.message;
                    }
                    resolve(success.result);
                  } else {
                    resolve(success)
                  }
                }

            },
            error => {
              reject(error);
            }
        );
      }
  )
}

const assembly = (param, cmd) => {
  let outer = [
    {
      'id': 0,
      'command': cmd, // 'com.agilecontrol.fair.MiscCmd'
      //   com.agilecontrol.fair.FairCmd
      'params': {
        'parentnode': -1,
        // 'cmd': 'com.agilecontrol.fair.cmd.IMContact',
        // 'params': param
        ...param
      }
    }];
  return { transactions: outer };
};

export default $fairCmd;
